<?php
// +----------------------------------------------------------------------
// | CSMITSM  [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2024 https://www.fastadmin.net All rights reserved.
// +----------------------------------------------------------------------
// | Author: chenshiming
// +----------------------------------------------------------------------

namespace app\admin\controller\csmitsm;

use addons\csmitsm\library\xcore\xcflow\utils\XcflowallformUtils;
use think\Db;
use addons\csmitsm\library\xcore\xcore\base\XcABackend;
use addons\csmitsm\library\xcore\xcore\utils\XcRequestUtils;
use addons\csmitsm\library\xcore\xcflow\utils\XcformPageUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcAdminSessionUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcDatabaseUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcResponseUtils;
use addons\csmitsm\library\xcore\xcore\XcException;

class Xcflowviewpageviewdata extends XcABackend
{

    /**
     * Xcflowviewpageview模型对象
     * @var \app\admin\model\csmitsm\Xcflowviewpageview
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\csmitsm\Xcflowviewpageview;
        $this->assign("statusList", $this->model->getStatusList());
    }

    public function indexajax()
    {
        $page_id = XcRequestUtils::get("page_id", true);
        $view_id = XcRequestUtils::get("view_id");
        $view = XcformPageUtils::getViewIfNullThenFirstView($page_id, $view_id);

        $total = 0;
        $rows = [];
        $showfieldcodes = [];
        if (!empty($view->tablename)) {
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $tablename = XcDatabaseUtils::getFactTablename($view['tablename']);
            $sql = Db::table($tablename)->where($where);

            // sql_orderby
            $orderbys = [];
            if (isset($view['configjsonObj']['orderbyfields'])) {
                foreach ($view['configjsonObj']['orderbyfields'] as $item) {
                    if ($item['selected'] == "Y") {
                        $orderby = isset($item["orderby"]) ? $item["orderby"] : "asc";
                        $orderbys[] = $item["fieldcode"] . " " . $orderby;
                    }
                }
            }
            $sql->order($orderbys);

            // sql_fields
            foreach ($view['configjsonObj']['showfields'] as $showfield) {
                if ($showfield['selected'] == 'Y') {
                    $showfieldcodes[] = $showfield['fieldcode'];
                }
            }
            $sql->field($showfieldcodes);

            // sql_where
            if (isset($view['configjsonObj']['filterfields'])) {
                foreach ($view['configjsonObj']['filterfields'] as $item) {
                    if ($item['selected'] == "Y") {
                        if (!empty($item["el"])) {
                            switch ($item["el"]) {
                                case "BETWEEN":
                                    $sql->where($item["fieldcode"], $item["el"], [$item["elvalue1"], $item["elvalue2"]]);
                                    break;
                                case "in":
                                case "notin":
                                    $value = isset($item["elvalue"]) ? explode(",", $item["elvalue"]) : [];
                                    $sql->where($item["fieldcode"], $item["el"], $value);
                                    break;
                                case "in_sql":
                                    $elvalue = (isset($item["elvalue"]) ? $item["elvalue"] : null);
                                    $elvalue = str_replace("'", "‘", $elvalue);
                                    $elvalue = str_replace("--", "－－", $elvalue);
                                    if ($elvalue != null) {
                                        $elvalue = str_replace('[[sessionadminid]]', XcAdminSessionUtils::getUserId(), $elvalue);
                                    }
                                    $sql->where("{$item['fieldcode']} in ({$elvalue})");
                                    break;
                                default:
                                    $elvalue = (isset($item["elvalue"]) ? $item["elvalue"] : null);
                                    // replace {{sessionadminid}} 
                                    if ($elvalue != null) {
                                        $elvalue = str_replace('[[sessionadminid]]', XcAdminSessionUtils::getUserId(), $elvalue);
                                    }
                                    $sql->where($item["fieldcode"], $item["el"], $elvalue);
                            }
                        }
                    }
                }
            }
            if (isset($view['configjsonObj']['filtersql'])) {
                $filtersql = XcformPageUtils::processFiltersql($view['configjsonObj']['filtersql']);
                $sql->where($filtersql);
            }
            $list = $sql->paginate($limit);

            $total = $list->total();
            $rows = $list->items();
        }

        // convert list_value (xcform_control_objselect/xcform_control_objselectmulti...)
        if ($total > 0) {
            $xcfieldjsonObj = XcformPageUtils::getXcfieldjsonObjByTablename($view->tablename);
            foreach ($showfieldcodes as $showfieldcode) {
                foreach ($xcfieldjsonObj as $fieldjson) {
                    if (isset($fieldjson['fieldcode']) && $fieldjson['fieldcode'] == $showfieldcode) {
                        if (!in_array($showfieldcode, ["id"])) {
                            switch ($fieldjson['fieldtag']) {
                                case "xcform_control_objselect":
                                    $tablename = $fieldjson['fieldjsonObj']['xcform_base_selecttablefield']['tablename'];
                                    $tableinfo = XcflowallformUtils::getTableinfoByTablename($tablename);
                                    XcDatabaseUtils::bindDbListColumn($rows, $showfieldcode, $tablename, null, [$tableinfo['displayfieldcode']]);
                                    break;
                                case "xcform_control_objselectmulti":
                                    $tablename = $fieldjson['fieldjsonObj']['xcform_base_selecttablefield']['tablename'];
                                    $tableinfo = XcflowallformUtils::getTableinfoByTablename($tablename);
                                    XcDatabaseUtils::bindDbListMultiColumn($rows, $showfieldcode, $tablename, null, $tableinfo['displayfieldcode']);
                                    break;
                            }
                        }
                    }
                }
            }
        }

        $result = ['total' => $total, 'rows' => $rows];

        return json($result);
    }

    public function index()
    {
        $page_id = XcRequestUtils::get("page_id", true);
        $view_id = XcRequestUtils::get("view_id");

        $views = XcformPageUtils::getViewsByPageid($page_id);
        $view = XcformPageUtils::getViewIfNullThenFirstView($page_id, $view_id);

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $xcfieldjsonObj = null;
            if (!empty($view->tablename)) {
                $xcfieldjsonObj = XcformPageUtils::getXcfieldjsonObjByTablename($view->tablename);
            }

            $this->view->assign("view_id", $view ? $view->id : null);
            $this->view->assign("page_id", $page_id);
            $this->view->assign("views", $views);
            $this->assignconfig("view", $view);
            $this->assignconfig("xcfieldjsonObj", $xcfieldjsonObj);

            return $this->view->fetch();
        }
    }

    public function createOrUpdateXcformPage()
    {
        $page_id = XcRequestUtils::get("page_id", true);
        $view_id = XcRequestUtils::get("view_id");

        $view = XcformPageUtils::getViewIfNullThenFirstView($page_id, $view_id);
        $targetTableinfo = $this->_getTargetTableinfoByView($view);


        switch ($targetTableinfo['xcformtype']) {
            case "flow":
                XcResponseUtils::redirect("csmitsm/xcmyflowinstance/createOrUpdateXcformPage?xcform_id=" . $targetTableinfo['xid']);
                break;
            case "flowsub":
            case "mdm":
                XcResponseUtils::redirect("csmitsm/xcflowmdmdata/createOrUpdateXcformPage?xcform_id=" . $targetTableinfo['xid']);
                break;
        }
    }

    public function showXcformPage() {
        $id = XcRequestUtils::get(["id","ids"] ,true);
        $page_id = XcRequestUtils::get("page_id", true);
        $view_id = XcRequestUtils::get("view_id");

        $view = XcformPageUtils::getViewIfNullThenFirstView($page_id, $view_id);
        $targetTableinfo = $this->_getTargetTableinfoByView($view);

        switch ($targetTableinfo['xcformtype']) {
            case "flow":
                XcResponseUtils::redirect("csmitsm/xcmyflowinstance/showXcformPage?xcform_id=" . $targetTableinfo['xid']."&id=".$id);
                break;
            case "flowsub":
            case "mdm":
                XcResponseUtils::redirect("csmitsm/xcflowmdmdata/showXcformPage?xcform_id=" . $targetTableinfo['xid']."&id=".$id);
                break;
        }
    }

    private function _getTargetTableinfoByView($view){
        $xcfieldjsonObj = XcformPageUtils::getXcfieldjsonObjByTablename($view->tablename);

        // get id_column's xcform_base_selecttablefield(xcflowfieldjson), for create&edit page_url
        $targetTableinfo = null;
        if(true){
            foreach($xcfieldjsonObj as $fieldjson){
                if(isset($fieldjson['fieldcode']) && $fieldjson['fieldcode']=='id'){
                    $targetTablename = $fieldjson['fieldjsonObj']['xcform_base_selecttablefield']['tablename'];
                    $targetTableinfo = XcflowallformUtils::getTableinfoByTablename($targetTablename);
                    break;
                }
            }
            if($targetTableinfo==null){
                throw new XcException("配置错误,视图缺少ID字段",0,null,"{$view->tablename}缺少ID字段,或ID字段缺少xcform_base_selecttablefield配置");
            }
        }

        return $targetTableinfo;
    }
}
